﻿using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.WebSockets;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using LitJson;
using static System.Net.WebRequestMethods;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace XMerp
{
    public class Model
    {
        private List<Shop> shops = new();

        private static HttpClient? client = new() { Timeout = TimeSpan.FromSeconds(30) };

        private static string token = string.Empty;

        private static ClientWebSocket ws = new();

        public Model()
        {
            // QueryMall();
            UserLogin();
        }

        public Task<JsonData> ModelFactory(string Key, params object[] Params)
        {
            switch (Key)
            {
                case "SearchByExpressNo":
                    var content = new StringContent(@$"{{""orderFlags"":[],""whId"":""1"",""platformCode"":"""",""mallCodes"":[],""orderCreateTimes"":[],""logisticsCodes"":[""{(string)Params[0]}""],""buyerNicks"":[],""receiveMobileL4"":"""",""receiveName"":"""",""receiveMobile"":"""",""senderName"":"""",""senderPhone"":"""",""senderMobile"":"""",""productNameL"":"""",""skuNameL"":"""",""skuCodeL"":"""",""productCodeL"":"""",""goodsOrSkuCnt"":"""",""waybillPrintStatusList"":[0,1],""deliverPrintStatusList"":[0,1],""hasGift"":"""",""orderTypeList"":[],""orderTags"":[],""statusList"":[],""orderStatusList"":[],""hasWaybillNo"":"""",""hasExpress"":"""",""cpCodeTempId"":"""",""receiveAreas"":[],""supplierIds"":[],""distributorIds"":[],""pageIndex"":600,""pageNo"":1,""limit"":500,""orderByIndex"":""13""}}", Encoding.UTF8, "application/json");
                   
                    return Page(content);

                case "SetSysWords":                   
                    return SetSysWords(Params);

                case "Send" :
                    return Send(Params);

                case "ApplyWaybill":
                    return ApplyWaybill(Params);

               
            }
            return null;
        }













        //底层http请求
        private HttpRequestMessage BaseHttpRequest(HttpMethod method, string url, HttpContent content)
        {
            var request = new HttpRequestMessage(method, url);
            request.Content = content;
            request.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0");
            request.Headers.Add("Accept", "application/json");
            request.Headers.Add("accept-encoding", "gzip");
            request.Headers.Add("jwt-token", @$"{token}");
            return request;
        }

        private async void UserLogin()
        {
            StringContent content = null;
            HttpRequestMessage request = null;
            HttpResponseMessage response = null; ;
            JsonData jsonObject = null;
            try
            {
                content = new StringContent(@"{""sessionId"":"""",""username"":""18640194060"",""password"":""Malijia2!"",""graphicsCode"":""""}", Encoding.UTF8, "application/json");
                request = BaseHttpRequest(HttpMethod.Post, "https://erp.yto.net.cn/steward/erp/users/userLogin", content);
                response = await client.SendAsync(request);
                jsonObject = response.Content.ToJsonData();
                if (jsonObject["code"].ToString()== "200")
                {
                    token = jsonObject["data"]["token"].ToString();
                }
                else
                {
                    jsonObject.ToTXT();
                }
            }
            finally
            {
                if (null != content) content.Dispose();
                if (null != request) request.Dispose();
                if (null != response) response.Dispose();
                if (null != jsonObject) { jsonObject.Clear(); jsonObject = null; }
            }
        }
        private async void QueryMall()
        {
            StringContent content = null;
            HttpRequestMessage request = null;
            HttpResponseMessage response = null; ;
            JsonData jsonObject = null;
            try
            {
                content = new StringContent(@"{""platformCode"":"""",""companyId"":2507,""userId"":""6d279c79c3984261a2217b7f1ab25849"",""pageNo"":1,""limit"":50,""status"":"""",""defineExpiredStatus"":"""",""id"":""""}", Encoding.UTF8, "application/json");
                request = BaseHttpRequest(HttpMethod.Post, "https://erp.yto.net.cn/erp/ecom-ms/commonMall/queryMall", content);
                response = await client.SendAsync(request);
                jsonObject = response.Content.ToJsonData();
                if (jsonObject["message"].ToString() == "ok")
                {
                    foreach (JsonData i in jsonObject["data"]["items"])
                    {
                        var endTime = Convert.ToDateTime(i["serviceEndTime"].ToString()).ToFileTime();
                        if (endTime < DateTime.Now.ToFileTime()) continue;

                        shops.Add(new Shop
                        {
                            mallId = (string)i["id"],
                            mallCode = (string)i["mallCode"],
                            mallName = (string)i["mallName"],
                            PlatformCode = (string)i["platformCode"],
                            platformName = (string)i["platformName"],
                            shopsEndTime = endTime,
                        });
                    }
                }
                else
                {
                    jsonObject.ToTXT();
                }
            }
            finally
            {
                if (null != content) content.Dispose();
                if (null != request) request.Dispose();
                if (null != response) response.Dispose();
                if (null != jsonObject) { jsonObject.Clear(); jsonObject = null; }
            }
        }
        private async Task<JsonData> Page(StringContent content)
        {
            HttpRequestMessage request = null;
            HttpResponseMessage response = null; ;
            JsonData jsonObject = null;
            try
            {
                request = BaseHttpRequest(HttpMethod.Post, "https://erp.yto.net.cn/erp/ecom-order/order/v2/tab/page", content);
                response = await client.SendAsync(request);
                jsonObject = response.Content.ToJsonData();       
            }
            finally
            {
                if (null != request) request.Dispose();
                if (null != response) response.Dispose();
            }
            return jsonObject;
        }

        private async Task<JsonData> SetSysWords(params object[] Params)
        {
            StringContent content = null;
            HttpRequestMessage request = null;
            HttpResponseMessage response = null; ;
            JsonData jsonObject = null;
            try
            {
                content = new StringContent(@$"{{""orderList"":[{{""id"":""{Params[0].ToString()}"",""sysOrderId"":""{Params[1].ToString()}"",""orderId"":""{Params[2].ToString()}""}}],""sysWords"":""{Params[3].ToString()}""}}", Encoding.UTF8, "application/json");
                request = BaseHttpRequest(HttpMethod.Post, "https://erp.yto.net.cn/erp/ecom-order/order/setSysWords", content);
                response = await client.SendAsync(request);
                jsonObject = response.Content.ToJsonData();
                if (jsonObject["message"].ToString() != "ok")
                {
                    jsonObject.ToTXT();
                    Controller.speech.SpeakAsync("系统备注添加失败");
                }
            }
            finally
            {
                if (null != content) content.Dispose();
                if (null != request) request.Dispose();
                if (null != response) response.Dispose();
                if (null != jsonObject) { jsonObject.Clear(); jsonObject = null; }
            }
            return null;
        }

        private async Task<JsonData> Send(params object[] Params)
        {
            StringContent content = null;
            HttpRequestMessage request = null;
            HttpResponseMessage response = null; ;
            JsonData jsonObject = null;
            JsonData res = null;
            try
            {//
                jsonObject = (Params[0] as JsonData)["data"]["items"][0];
                content = new StringContent(@$"{{""orderInfos"":[{{""cpCode"":""{jsonObject["cpCode"].ToString()}"",""id"":""{jsonObject["id"].ToString()}"",""logisticsCode"":""{jsonObject["waybillNo"].ToString()}"",""mergeFlag"":{jsonObject["mergeFlag"].ToString()},""orderId"":""{jsonObject["orderId"].ToString()}"",""platformCode"":""{jsonObject["platformCode"].ToString()}"",""sysOrderId"":""{jsonObject["sysOrderId"].ToString()}"",""subIds"":""{(jsonObject.ContainsKey("mergeOrderIds") ? jsonObject["mergeOrderIds"].ToString() : "")}"",""packgeId"":""""}}]}}", Encoding.UTF8, "application/json");
                request = BaseHttpRequest(HttpMethod.Post, "https://erp.yto.net.cn/erp/ecom-order/delivery/send", content);
                response = await client.SendAsync(request);
                res = response.Content.ToJsonData();
                if (res["message"].ToString() != "ok")
                {
                    res.ToTXT();
                    Controller.speech.SpeakAsync("发货请求失败");
                }
            }
            finally
            {
                if (null != content) content.Dispose();
                if (null != request) request.Dispose();
                if (null != response) response.Dispose();
                if (null != jsonObject) { jsonObject.Clear(); jsonObject = null; }
            }
            return res;
        }


        private async Task<JsonData> ApplyWaybill(params object[] Params)
        {
            var checkProduct = Params[0] as View_CheckProducts;
            StringContent content = null;
            HttpRequestMessage request = null;
            HttpResponseMessage response = null; ;
            JsonData res = null;
            try
            {//
              // MessageBox.Show(@$"{{""againApply"":1,""userId"":""6d279c79c3984261a2217b7f1ab25849"",""companyId"":2507,""mutilPackNum"":{checkProduct.input_mutilPackNum.Text},""ifHasBuildPackageAuthority"":false,""orderInfoRequests"":[{{""platformCode"":""{checkProduct.platformCode}"",""mallCode"":""{checkProduct.mallCode}"",""mallName"":""{checkProduct.mallName}"",""sysOrderId"":""{checkProduct.sysOrderId}"",""orderId"":""{checkProduct.orderId}"",""id"":""{checkProduct.id}"",""applyOrderType"":0,""cpCode"":""{checkProduct.cpCode}"",""cpCodeTempId"":""{checkProduct.cpCodeTempId}"",""logisticsName"":""{checkProduct.logisticsName}"",""subIds"":""{checkProduct.subIds}"",""logisticsCodes"":[],""mutilPackNum"":{checkProduct.input_mutilPackNum.Text},""distributorPlatformCode"":""""}}]}}");
                content = new StringContent(@$"{{""againApply"":1,""userId"":""6d279c79c3984261a2217b7f1ab25849"",""companyId"":2507,""mutilPackNum"":{checkProduct.iptMutilPack.Text},""ifHasBuildPackageAuthority"":false,""orderInfoRequests"":[{{""platformCode"":""{checkProduct.platformCode}"",""mallCode"":""{checkProduct.mallCode}"",""mallName"":""{checkProduct.mallName}"",""sysOrderId"":""{checkProduct.sysOrderId}"",""orderId"":""{checkProduct.orderId}"",""id"":""{checkProduct.id}"",""applyOrderType"":0,""cpCode"":""{checkProduct.cpCode}"",""cpCodeTempId"":""{checkProduct.cpCodeTempId}"",""logisticsName"":""{checkProduct.logisticsName}"",""subIds"":""{checkProduct.subIds}"",""logisticsCodes"":[],""mutilPackNum"":{checkProduct.iptMutilPack.Text},""distributorPlatformCode"":""""}}]}}", Encoding.UTF8, "application/json");
                request = BaseHttpRequest(HttpMethod.Post, "https://erp.yto.net.cn/erp/ecom-order/waybill/applyWaybill", content);
                response = await client.SendAsync(request);
                res = response.Content.ToJsonData();
                if (res["message"].ToString() != "ok")
                {
                    res.ToTXT();
                    Controller.speech.SpeakAsync("发货请求失败");
                }
            }
            finally
            {
                if (null != content) content.Dispose();
                if (null != request) request.Dispose();
                if (null != response) response.Dispose();
               
            }
            return res;
        }

        public async Task WebsocketConnect()
        {
            await ws.ConnectAsync(new("ws://127.0.0.1:3300/print"),default);

            Debug.WriteLine(ws.State);
        }

        public async Task WebsocketClose()
        {
            await ws.CloseAsync(WebSocketCloseStatus.NormalClosure,"打印完成",CancellationToken.None);
            Debug.WriteLine(ws.State);
        }

        public async Task WebsocketSend(string message)
        {
            await ws.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(message)), WebSocketMessageType.Text, true, CancellationToken.None);
        }


        public class Shop
        {
            public string mallId { get; set; }
            public string mallName { get; set; }
            public string mallCode { get; set; }
            
            public long shopsEndTime { get; set; }
            public string PlatformCode { get; set; }
            public string platformName { get; set; }
        }

    }
}
